<?php
// +-------------------------------------------------------------------
// | 
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Kcdns\Admin\Model;
use Kcdns\Admin\Common\ModelCfg;

class ConfigModel extends CommonModel
{
    
    // 批量读取配置
    public function batchGet ()
    {
        $names = [];
        $data = [];
        foreach ($this->cfg->formField as $k => $v)
        {
            list ($tmp, $names[]) = explode('.', $k);
        }
        $_data = $this->where([
                'name' => [
                        'in',
                        $names
                ]
        ])->select();
        foreach ($_data as $v)
        {
            $_setting = $this->cfg->formField[$this->name . '.' . $v['name']];
            $data[$this->name . '.' . $v['name']] = kcone_think_decrypt($v['value']);
            
            // 修正图片字段
            $_setting['type'] == 'picture' and $data[$_setting['name']] = $this->_idToImage($data[$_setting['name']]);
            $_setting['type'] == 'file' and $data[$_setting['name']] = $this->_idToFile($data[$_setting['name']]);
        }
        return $data;
    }
    
    // 批量修改配置
    public function batchSet ($data)
    {
        $cfgNameArr = explode('/', $this->cfg->name);
        $cfgName = end($cfgNameArr);
        
        $formData = $this->_getFormData($data);
        foreach ($formData[$this->name] as $k => $v)
        {
            $_setting = $this->cfg->formField[$this->name . '.' . $k];
            $_exists = $this->where([
                    'name' => $k
            ])->find();
            
            $_config = [
                    'name' => $k,
                    'title' => $_setting['title'],
                    'remark' => $_setting['remark'],
                    'value' => kcone_think_encrypt($v), // 加密存储配置
                    'group' => $cfgName,
                    'update_time' => date('Y-m-d H:i:s')
            ];
            if ($_exists)
            {
                $this->data($_config)->where([
                        'name' => $k
                ])->save();
            }
            else
            {
                $_config['create_time'] = date('Y-m-d H:i:s');
                $this->data($_config)->add();
            }
        }
        
        $this->clear();
        return true;
    }

    protected function _insert ($formData, $fillData = [])
    {
        $status = parent::_insert($formData, $fillData) and $this->clear();
        return $status;
    }

    protected function _update ($formData = [], $where = [])
    {
        $status = parent::_update($formData, $where) and $this->clear();
        return $status;
    }

    protected function _del ($delOptions)
    {
        $status = parent::_del($delOptions) and $this->clear();
        return $status;
    }
    
    // 数据发生变化时清空配置缓存
    public function clear ()
    {
        S('DB_CONFIG_CACHE', null);
        return true;
    }
    
    // 导出系统配置 : 模型配置, 菜单, 字典
    public function export ()
    {
        $sysConfig = [
                'menu' => M('Menu')->select(),
                'cfgx' => M('config')->field('name,value')->where([
                        'group' => 'model'
                ])->select(),
                'dic' => M('dic')->select(),
                'dic_item' => M('dic_item')->select()
        ];
        return json_encode($sysConfig);
    }
    
    // 导入系统配置
    public function import ($data)
    {
        // 菜单同步 获取同步菜单数据
        $data = json_decode($data['config.import'], true);
        $menus = $data['menu'];
        $cfgx = $data['cfgx'];
        $dic = $data['dic'];
        $dicItem = $data['dic_item'];
        
        $dir = ROOT_PATH . "Data/Backup/Import/";
        file_exists($dir) or mkdir($dir, 0777, true) and chmod($dir, 0777);
        file_put_contents($dir . date('Y-m-d[H-i-s]') . '.json', $this->export());
        
        // 导入前 清除menu表
        if ($menus)
        {
            $bakMenus = M('Menu')->select();
            M('Menu')->where('1=1')->delete();
            $res = M('Menu')->addAll($menus);
            if ($res === false)
            {
                // 同步失败 数据还原
                $bakStatus = M('Menu')->addAll($bakMenus);
                E('菜单同步失败:已执行还原(还原' . ($bakStatus === false ? '失败' : '成功') . ')');
            }
        }
        
        // 更新 cfgx
        if ($cfgx)
        {
            $c = new ModelCfg('-', '', true);
            M('config')->field('name,value')->where([
                    'name' => [
                            'like',
                            'MODEL_CFG_%'
                    ]
            ])->delete();
            foreach ($cfgx as $v)
            {
                $c->save(substr($v['name'], strlen('MODEL_CFG_')), $v['value']) or E('更新 CFGX 失败');
            }
        }
        
        // 更新字典分类
        if ($dic)
        {
            M('dic')->where('1=1')->delete();
            $res = M('dic')->addAll($dic);
            if ($res === false)
            {
                E('同步字典分类失败');
            }
        }
        
        // 更新字典
        if ($dicItem)
        {
            M('dic_item')->where('1=1')->delete();
            $res = M('dic_item')->addAll($dicItem);
            if ($res === false)
            {
                E('同步字典失败');
            }
        }
        
        return true;
    }
    
    // 微信设置
    public function batchSetWechat ($data)
    {
        $status = $this->batchSet($data);
        if ($status)
        {
            // TODO : 自动生成 oauth 配置
            if ($data['WECHAT_OAUTH'])
            {}
            else
            {}
            
            // TODO : 自动生成支付配置
            if ($data['WECHAT_PAY'])
            {}
            else
            {}
        }
        return $status;
    }
}